package com.fly.mulprogress.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.NonNull;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.widget.ProgressBar;

/**
 * Created with Android Studio.
 * Package_Name：com.fly.mulprogress.view
 * Project_Name：MulProgress
 * User：郭鹏飞
 * Date：2016/1/6
 * Email：love518420@foxmail.com
 * Description：
 */
public class CircleProgressBar extends ProgressBar {

    RectF rect;
    float dynamicSweepAngle = 0f;
    Paint pbPaint, circlePaint;
    TextPaint txtPaint;

    boolean flag = true;

    public CircleProgressBar(Context context) {
        this(context, null);
    }

    public CircleProgressBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        rect = new RectF(20, 20, 100, 100);
        pbPaint = new Paint();
        pbPaint.setAntiAlias(true);
        pbPaint.setStyle(Paint.Style.STROKE);
        pbPaint.setStrokeWidth(15);
        pbPaint.setDither(true); // 防抖动
        pbPaint.setStrokeCap(Paint.Cap.ROUND); // 笔刷类型
        pbPaint.setColor(Color.RED);

        circlePaint = new Paint();
        circlePaint.setAntiAlias(true);
        circlePaint.setStyle(Paint.Style.STROKE);
        circlePaint.setStrokeWidth(5);
        circlePaint.setColor(Color.GRAY);

        txtPaint = new TextPaint();
        txtPaint.setStyle(Paint.Style.FILL);
        txtPaint.setColor(Color.BLUE);
        txtPaint.setTextSize(15);
    }

    @Override
    protected synchronized void onDraw(@NonNull Canvas canvas) {
        super.onDraw(canvas);

        if (flag) {
            canvas.drawCircle(60, 60, 40, circlePaint);

            canvas.drawArc(rect, 0f, dynamicSweepAngle, false, pbPaint);

            canvas.drawText(getProgress() + "%", 48, 65, txtPaint);
        }
    }
int x;
    public void start() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (dynamicSweepAngle < 360f) {
                    dynamicSweepAngle = 360f * getProgress() / getMax();
                    dynamicSweepAngle = dynamicSweepAngle > 360f ? 360f : dynamicSweepAngle;
                    setProgress(x += 2);
                    postInvalidate();
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                flag = false;
            }
        }).start();
    }
}
